package spider_lib

// 基础包
import (
    "github.com/henrylee2cn/pholcus/app/downloader/request" //必需
    . "github.com/henrylee2cn/pholcus/app/spider" //必需
    "fmt"
    "github.com/PuerkitoBio/goquery"
    "regexp"
    "strings"
    "time"
)

var date_exp = regexp.MustCompile(`\s*(\d+):(\d+)\s+(AM|PM)\s*((\d+)/(\d+))?\s*`)
var date2_exp = regexp.MustCompile(`(\d+)/(\d+)/(\d+)`)

func init() {
    bwin.Register()
}

var bwin = &Spider{
    Name:        "bwin",
    Description: "Online Betting, Poker & Casino | Bet online with bwin",
    EnableCookie: false,
    NotDefaultField: true,
    RuleTree: &RuleTree{
        Root: func(ctx *Context) {
            for cate, cid := range map[string]int{
                "Football":4,
                "Tennis":5,
                "Ice Hockey":12,
                "Basketball":7,
                "Volleyball":18,
                "Handball":16,
                //"Formula 1":6,
                //"Motorbikes":40,
                "Rugby Union":32,
                "Rugby League":31,
                "Cricket":22,
                //"Boxing":24,
                //"Golf":13,
                "Darts":34,
                "Baseball":23,
                //"Alpine Skiing":9,
                //"American Football":11,
                //"Aussie Rules":36,
                //"Beach Volleyball":63,
                //"Biathlon":64,
                //"Chess":67,
                //"Combat sports":45,
                //"Cross Country Skiing":94,
                //"Cycling":10,
                //"Entertainment":60,
                "Futsal":70,
                //"NASCAR":39,
                //"Netball":73,
                //"Politics":61,
                //"Rally":43,
                //"Ski Jumping":95,
                //"Snooker":33,
                //"Specials":25,
                //"Speedway":42,
                //"Swimming":51,
            } {
                ctx.AddQueue(&request.Request{
                    Url:  fmt.Sprintf("https://sports.bwin.com/en/sports/indexmultileague?cate=%s", cate),
                    Rule: "列表",
                    Method: "POST",
                    Header: formHeader,
                    PostData: "sportId=4&page=0",
                    Temp: map[string]interface{}{"cate": cate, "sport":ToStr(cid)},
                    Reloadable: true,
                })
            }
        },

        Trunk: map[string]*Rule{
            "列表":{
                ParseFunc: func(ctx *Context) {
                    var cate string
                    var sport string
                    ctx.GetTemp("cate", &cate)
                    ctx.GetTemp("sport", &sport)
                    pages := ctx.GetDom().Find(".pagination .page-link a")
                    count := ToNum(pages.Eq(pages.Size() - 2).Text())
                    for i := 1; i <= count; i++ {
                        ctx.AddQueue(&request.Request{
                            Url: fmt.Sprintf("https://sports.bwin.com/en/sports/indexmultileague?cate=%s&page=%d", cate, i - 1),
                            Rule: "获取细节",
                            Method: "POST",
                            Header: formHeader,
                            PostData: fmt.Sprintf("sportId=%s&page=%d", sport, i - 1),
                            Temp: map[string]interface{}{"cate": cate},
                        })
                    }
                },
            },

            "获取细节":{
                ItemFields: []string{
                    "cate",
                    "time",
                    "lh",
                    "rh",
                    "bets",
                },
                ParseFunc: func(ctx *Context) {
                    var cate string
                    ctx.GetTemp("cate", &cate)
                    ctx.GetDom().Find(".ui-widget-content-body").Each(func(i int, s *goquery.Selection) {
                        // 分组
                        s.Find(".listing").Each(func(ii int, ss *goquery.Selection) {
                            td := ss.Find("td")
                            lh := td.Eq(0).Find("button span").Text()
                            bets := td.Eq(1).Find(".odds").Text()
                            rh := td.Eq(2).Find("button span").Text()
                            timestr := strings.Replace(ss.Find("h6").Text(), "\n", "", -1)
                            ret := date_exp.FindAllStringSubmatch(timestr, -1)[0]
                            year := time.Now().Year()
                            hour := ToNum(ret[1])
                            minute := ToNum(ret[2])
                            if ret[3] == "PM" {
                                hour += 12
                            }
                            month := time.Month(ToNum(ret[5]))
                            day := ToNum(ret[6])
                            if ret[4] == "" {
                                ret2 := date2_exp.FindAllStringSubmatch(s.Find(".event-group-level3").Text(), -1)[0]
                                month = time.Month(ToNum(ret2[1]))
                                day = ToNum(ret2[2])
                                year = ToNum(ret2[3])
                            }
                            timestr = time.Date(year, month, day, hour, minute, 0, 0, time.UTC).Format("2006-01-02 15:04:05")
                            ctx.Output(map[int]interface{}{
                                0:cate,
                                1:timestr,
                                2:lh,
                                3:rh,
                                4:bets,
                            })
                        });
                    });
                },
            },
        },
    },
}